﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Reflection;
using System.ComponentModel;

namespace Kaiser.Extensions
{
    public static class DataTableExtensions
    {
        public static string DataTable2Json(this DataTable dt)
        {
            if (dt.Rows.Count == 0)
            {
                return "";
            }
            StringBuilder jsonBuilder = new StringBuilder();
            // jsonBuilder.Append("{");
            //jsonBuilder.Append(dt.TableName.ToString()); 
            jsonBuilder.Append("[");//转换成多个model的形式
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                jsonBuilder.Append("{");
                for (int j = 0; j < dt.Columns.Count; j++)
                {
                    jsonBuilder.Append("\"");
                    jsonBuilder.Append(dt.Columns[j].ColumnName);
                    jsonBuilder.Append("\":\"");
                    jsonBuilder.Append(dt.Rows[i][j].ToString());
                    jsonBuilder.Append("\",");
                }
                jsonBuilder.Remove(jsonBuilder.Length - 1, 1);
                jsonBuilder.Append("},");
            }
            jsonBuilder.Remove(jsonBuilder.Length - 1, 1);
            jsonBuilder.Append("]");
            //  jsonBuilder.Append("}");
            return jsonBuilder.ToString();
        }
 

        /// <summary>
        /// 将DataTable转换为list
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="dt"></param>
        /// <returns></returns>
        public static IList<T> ToList<T>(this DataTable dt)
        {
            if (dt == null)
                return null;
            IList<T> result = new List<T>();
            for (int j = 0; j < dt.Rows.Count; j++)
            {
                T _t = (T)Activator.CreateInstance(typeof(T));
                PropertyInfo[] propertys = _t.GetType().GetProperties();
                foreach (PropertyInfo pi in propertys)
                {
                    var fieldName = string.Empty;


                    fieldName = pi.Name;


                    for (int i = 0; i < dt.Columns.Count; i++)
                    {
                        // 属性与字段名称一致的进行赋值 
                        if (fieldName.Equals(dt.Columns[i].ColumnName, StringComparison.OrdinalIgnoreCase))
                        {
                            if (dt.Rows[j][i] != DBNull.Value)
                            {
                                var strPropertyType = pi.PropertyType.ToString();

                                if (strPropertyType == "System.Int32" || strPropertyType == typeof(int?).ToString())
                                {
                                    pi.SetValue(_t, Int32.Parse(dt.Rows[j][i].ToString()), null);
                                    break;
                                }
                                if (strPropertyType == "System.DateTime" || strPropertyType == typeof(DateTime?).ToString())
                                {
                                    pi.SetValue(_t, Convert.ToDateTime(dt.Rows[j][i].ToString()), null);
                                    break;
                                }
                                if (strPropertyType == "System.String")
                                {
                                    pi.SetValue(_t, dt.Rows[j][i].ToString(), null);
                                    break;
                                }
                                if (strPropertyType == "System.Boolean")
                                {
                                    var value = dt.Rows[j][i].ToString();
                                    if (value.ToString().EndsWith(true.ToString(), StringComparison.OrdinalIgnoreCase) ||
                                        value.ToString().EndsWith(false.ToString(), StringComparison.OrdinalIgnoreCase))
                                    {
                                        pi.SetValue(_t, Convert.ToBoolean(value), null);
                                    }
                                    else
                                    {
                                        pi.SetValue(_t, Convert.ToBoolean(int.Parse(value)), null);
                                    }
                                    break;
                                }
                                pi.SetValue(_t, Convert.ChangeType(dt.Rows[j][i], dt.Rows[j][i].GetType()), null);
                            }
                            else
                                pi.SetValue(_t, null, null);
                            break;
                        }
                    }
                }
                result.Add(_t);
            }
            return result;
        }

    }
}
